package org.example.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.entity.PageBean;
import org.example.mapper.ArticleMapper;
import org.example.model.Article;
import org.example.service.ArticleService;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void create(Article article) {
        articleMapper.create(article);
    }

    @Override
    public Article[] list() {
        return new Article[0];
    }

    @Override
    public PageBean<Article> list(Integer pageIndex, Integer pageSize, String title) {
        PageBean<Article> pageBean = new PageBean<>();

        // 开启分页查询 ,需要先在 pom.xml 中引入 PageHelper 依赖
        PageHelper.startPage(pageIndex, pageSize);

        // 获取用户id
        Integer userId = ThreadLocalUtil.getClaimsByKey("id");

        List<Article> list = articleMapper.list(pageIndex, pageSize, title, userId);

        // Page中提供了方法，可以获取PageHelper分页查询后，得到的总记录数
        Page<Article> obj = (Page<Article>) list;

        // 把数据填充到 PageBean 对象中
        pageBean.setList(obj.getResult());
        pageBean.setTotal(obj.getTotal());

        return  pageBean;
    }
}
